import React, { FC, memo, useEffect, useRef } from "react"
import { message } from "antd"
import rrwebPlayer from "rrweb-player"
import type { eventWithTime } from "@rrweb/types"
import { getRecordScreenService } from "@/service/record-screen"
import { unzip } from "@/utils/recordScreen"

type PropsType = {
    recordScreenId: string
}
const Player: FC<PropsType> = (props: PropsType) => {
    const { recordScreenId } = props

    const videoRef = useRef<HTMLDivElement>(null)
    const playerRef = useRef<rrwebPlayer | null>(null)

    useEffect(() => {
        async function initPlayer() {
            try {
                const result = await getRecordScreenService({ recordScreenId: recordScreenId })

                if (!result?.events) {
                    message.warning("暂无数据，请稍后再试~")
                    return
                }
                // 解压数据
                const eventsData: eventWithTime[] = unzip(result.events)

                // 销毁旧的播放器实例
                if (playerRef.current) {
                    playerRef.current.pause()
                    playerRef.current = null
                }

                // 初始化播放器
                if (videoRef.current) {
                    playerRef.current = new rrwebPlayer({
                        target: videoRef.current,
                        props: { events: eventsData }
                    })
                }
            } catch (error) {
                message.error("加载录屏失败")
            }
        }
        initPlayer()

        return () => {
            // 卸载组件时销毁播放器实例
            if (playerRef.current) {
                playerRef.current.pause()
                playerRef.current = null
            }
        }
    }, [recordScreenId])

    return <div style={{ display: "flex", justifyContent: "center", alignItems: "center", paddingTop: "-24px" }} ref={videoRef} />
}

export default memo(Player)
